package com.lorenzogao.pley.common.http

import android.content.Context
import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.lorenzogao.pley.common.Constant
import com.lorenzogao.pley.common.util.ACache
import com.lorenzogao.pley.common.util.DensityUtil
import com.lorenzogao.pley.common.util.DeviceUtils
import okhttp3.*
import java.util.*

/**
 * 作者：Lorenzo Gao
 * Date: 2018/1/3
 * Time: 10:15
 * 邮箱：2508719070@qq.com
 * Description:
 */
class CommonParamsInterceptor constructor(gson: Gson, context: Context) : Interceptor {


    companion object {
        val JSON: MediaType = MediaType.parse("application/json;charset=utf-8")
    }


    private var mGson: Gson = gson

    private var mContext: Context = context

    override fun intercept(chain: Interceptor.Chain?): Response {

        var request = chain!!.request()


        try {
            var method = request.method()

            var commonParams = HashMap<String, Any>()

            var imei = DeviceUtils.getIMEI(mContext)

            if (imei != null && imei.startsWith("000000")) {
                imei = "5284047f4ffb4e04824a2fd1d1f0cd62"
            }

            commonParams.put(Constant.IMEI, imei)
            commonParams.put(Constant.MODEL, DeviceUtils.model)
            commonParams.put(Constant.LANGUAGE, DeviceUtils.language)
            commonParams.put(Constant.os, DeviceUtils.buildVersionIncremental)
            commonParams.put(Constant.RESOLUTION, DensityUtil.getScreenW(mContext).toString() + "*" + DensityUtil.getScreenH(mContext))
            commonParams.put(Constant.SDK, DeviceUtils.buildVersionSDK)
            commonParams.put(Constant.DENSITY_SCALE_FACTOR, mContext.resources.displayMetrics.density.toString() + "")

            var token = ACache.get(mContext).getAsString(Constant.TOKEN)

            commonParams.put(Constant.TOKEN, if (token == null) "" else token)





            if (TextUtils.equals(method, "GET")) {

                var httpUrl = request.url()

                var rootMap = hashMapOf<String, Any>()

                var paramNames: Set<String> = httpUrl.queryParameterNames()

                for (key in paramNames) {
                    if (TextUtils.equals(Constant.PARAM, key)) {
                        var oldParamJson = httpUrl.queryParameter(Constant.PARAM)
                        if (oldParamJson != null) {
                            var p = mGson.fromJson(oldParamJson, hashMapOf<String, Any>()::class.java)//原始参数

                            if (p != null) {
                                for (entry in p) {
                                    rootMap.put(entry.key, entry.value)
                                }
                            }
                        }
                    } else {
                        rootMap.put(key, httpUrl.queryParameter(key))
                    }

                }

                rootMap.put("publicParams", commonParams)

                var newJsonParams = mGson.toJson(rootMap)

                var url = httpUrl.toString()

                var index = url.indexOf("?")

                if (index > 0) {
                    url = url.substring(0, index)
                }
                url = url + "?" + Constant.PARAM + "=" + newJsonParams
                request = request.newBuilder().url(url).build()

            } else if (TextUtils.equals(method, "POST")) {

                var body: RequestBody? = request.body()

                var rootMap = hashMapOf<String, Any>()

                if (body is FormBody) {//from表单
                    for (i in 0 until body.size()) {
                        rootMap.put(body.encodedName(i), body.encodedValue(i))
                    }
                } else {
                    var buffer = okio.Buffer()

                    body!!.writeTo(buffer)

                    var oldParamJson = buffer.readUtf8()
                    if (!TextUtils.isEmpty(oldParamJson)) {
                        rootMap = mGson.fromJson(oldParamJson, hashMapOf<String, Any>()::class.java)//原始参数
                        if (rootMap != null) {
                            rootMap.put("publicParams", commonParams)
                            var newJsonParams = mGson.toJson(rootMap)
                            request = request.newBuilder().post(RequestBody.create(JSON, newJsonParams)).build()
                        }
                    }
                }
            }
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
        }


        return chain!!.proceed(request)
    }


}

